//
//  FlipsideViewController.m
//  PhotoBase
//
//  Created by Alec Flett on 11/16/09.
//  Copyright __MyCompanyName__ 2009. All rights reserved.
//

#import "FlipsideViewController.h"
#import "Freebase.h"

@implementation FlipsideViewController

@synthesize delegate;
@synthesize usernameLabel = _usernameLabel;
@synthesize passwordLabel = _passwordLabel;
@synthesize loginButton = _loginButton;
@synthesize statusLabel = _statusLabel;
@synthesize sandboxSwitch = _sandboxSwitch;


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor]; 

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    _usernameLabel.text = [defaults objectForKey:@"freebase.username"];
    _passwordLabel.text = @"";
    _sandboxSwitch.on = [defaults boolForKey:@"freebase.use_sandbox"];
}

- (void)dealloc {
    self.delegate = nil;
    [super dealloc];
}

- (IBAction)login
{
    [[FreebaseSession session] login:self.usernameLabel.text 
                            password:self.passwordLabel.text
                            delegate:self didFinishSelector:@selector(loggedin:)];
    _statusLabel.text = @"Logging in...";
    _loginButton.enabled = _usernameLabel.enabled = _passwordLabel.enabled = NO;
}

- (void)errorDidOccur:(id)error request:(id<FreebaseRequest>)request
{
    _loginButton.enabled = _usernameLabel.enabled = _passwordLabel.enabled = YES;
    NSLog(@"oops, error in '%@': %@", request.name, error);
    _loginButton.enabled = YES;
    
    NSString *errorMessage;
    if ([error isKindOfClass:[NSDictionary class]]) {
        NSDictionary *errorDict = (NSDictionary*)error;
        errorMessage = [errorDict valueForKeyPath:@"messages.message"];
        if ([errorMessage isKindOfClass:[NSArray class]])
            errorMessage = [(NSArray*)errorMessage componentsJoinedByString:@", "];        
    } else
        errorMessage = [error description];
    _statusLabel.text = [NSString stringWithFormat:@"Error logging in: %@",
                         errorMessage];
}
- (IBAction)done {
	[self.delegate flipsideViewControllerDidFinish:self];	
}

- (void)loggedin:(id)result
{
    _loginButton.enabled = _usernameLabel.enabled = _passwordLabel.enabled = YES;
    NSLog(@"Loggedin: %@", result);
    _loginButton.enabled = YES;
    _statusLabel.text = @"Successfully logged in";
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.usernameLabel.text forKey:@"freebase.username"];
    [defaults setObject:self.passwordLabel.text forKey:@"freebase.password"];
    [self done];
}
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidDisappear:(BOOL)animated {
    [[NSUserDefaults standardUserDefaults] setBool:_sandboxSwitch.on forKey:@"freebase.use_sandbox"];
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _usernameLabel)
        [_passwordLabel becomeFirstResponder];
    else {
        [textField resignFirstResponder];
        [self login];
    }
    
    return YES;
}


- (IBAction)signup
{
    [[UIApplication sharedApplication] 
     openURL:[NSURL URLWithString:@"http://www.freebase.com/signin/register"]];      
}


@end
